#!/bin/bash
########################################################################
# script name:  check_legato_anf.sh
# Used for:
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2011/08/16    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for verifying Oracle backups

OPTIONS:
   -h               Host (comma separated)
   -r               Restricted (only those hosts with brbakup set to "y" in ba_host file)
   -w               HTML output

Ex.:
$0 -h saphrd01
STOP
}
#######################################
# Get parameters
#######################################
while getopts h:cwr OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | sed 's/,/ /g' | sed 's/^-*//' | cut -d. -f1 | tr '[A-Z]' '[a-z]')
                ;;
        w)
                WEB=1
					 ;;
        r)
                RESTRICTED=1
					 ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
#######################################
# Variables and environnement
#######################################
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
#######################################
# FUNCTIONS
#######################################
function pipescript {
cat << 'EOF' | sudo -u saunix ssh -q $1 "cat | sudo env SYS_NAME=$2 HOSTS=$1 bash"
function log {
	#HOSTS=`uname -n`
   DATE=`date +"%Y-%m-%d %H:%M:%S"`
	SEVERITY=$1
	COMMENT=$2

	case $SEVERITY in
		ERROR) NUM=1 ;;
		WARNING) NUM=2 ;;
		INFO) NUM=3 ;;
		OK) NUM=4 ;;
	esac

	echo "$NUM|$SEVERITY|$DATE|$HOSTS|$SYS_NAME|$STARTTIME|$STOPTIME|$COMMENT"
	exit 0
}
############################
# Setting values
############################
STOPTIME="N/A"
STARTTIME="N/A"
STOPTIME="N/A"
BKTYPE="N/A"
STATUS="N/A"

ANF_DIR=/oracle/$SYS_NAME/sapbackup
if [ ! -d "$ANF_DIR" ]; then log ERROR "No ANF_DIR ($ANF_DIR)"; fi
LAST_ANF=$(find $ANF_DIR/ -type f -prune -name '*.anf' -o -name '*.and' | xargs ls -1tr | tail -1)
if [ -z $LAST_ANF ]; then log ERROR "No ANF or AND file found in dir $ANF_DIR"; fi

TIME=$(cat $LAST_ANF | egrep 'Start of database backup|End of database backup' | awk '{print $(NF-1)" "$NF}' | sed 's/ /\//' | sed 's/$/,/' | xargs | sed 's/ //')
STARTTIME=$(echo $TIME | cut -d, -f1 | sed 's/\// /' | sed 's/\./:/g')
STOPTIME=$(echo $TIME | cut -d, -f2 | sed 's/\// /' | sed 's/\./:/g')

if [ `uname` = "AIX" ]; then DATE=/opt/freeware/bin/date; else DATE=/bin/date; fi
if [ ! -x $DATE ]; then log ERROR "GNU date missing (package coreutils rpm on AIX)"; fi

LAST=$($DATE -d "$STARTTIME" +%s)
NOW=$($DATE +%s)
DAYS_SINCE_LAST_BK=$(echo "scale=1;($NOW - $LAST)/60/60/24" | bc)
BKTYPE=$(cat $LAST_ANF | grep backup_type | awk '{print $NF}')
STATUS=$(cat $LAST_ANF | egrep 'BRBACKUP completed|BRBACKUP terminated' | tail -1 | awk '{print $NF}')

if [ -z "$STOPTIME" ]; then STOPTIME="N/A"; fi
if [ -z "$STARTTIME" ]; then STARTTIME="N/A"; fi
if [ -z "$STOPTIME" ]; then STOPTIME="N/A"; fi
if [ -z "$BKTYPE" ]; then BKTYPE="N/A"; fi
if [ -z "$STATUS" ]; then STATUS="N/A"; fi

############################
# Setting values
############################

if [[ "$STARTTIME" == "N/A" ]]; then log ERROR "Backup didn't started (STARTTIME=$STARTTIME $LAST_ANF)"; fi
if [[ "$STOPTIME" == "N/A" ]]; then log ERROR "Backup didn't finished (STOPTIME=$STOPTIME $LAST_ANF)"; fi
if [[ "$STATUS" == "warnings" ]]; then log WARNING "Backup didn't finished successfully ($STATUS $LAST_ANF)"; fi
if [[ "$STATUS" != "successfully" ]]; then log ERROR "Backup didn't finished successfully ($STATUS $LAST_ANF)"; fi
if [[ "$DAYS_SINCE_LAST_BK" > 1 ]]; then log WARNING "DAYS since last backup ($DAYS_SINCE_LAST_BK > 1 $LAST_ANF)"; fi
if [[ "$BKTYPE" != "online_cons" ]]; then log WARNING "BKTYPE != online_cons"; fi

log OK "Backup finished successfully"
EOF
}

#######################################
# MAIN
#######################################
TMPOUT="/tmp/${RANDOM}_`date +'%Y%m%d%H%M'`"
if [[ ! -z $RESTRICTED ]]
then
	NEWHOSTLIST=$(checkhost `list_hosts_brbackup | xargs` | grep -v Verifying)
else
	NEWHOSTLIST=$(checkhost $HOSTS | grep -v Verifying)
fi
NOT_VERIFIED_COUNT=0
for HOSTNAME in $NEWHOSTLIST
do
	if [ "$(list_brbackup_by_host $HOSTNAME)" == "n" ]
	then
		((NOT_VERIFIED_COUNT++))
	else
		SYS_NAME=$(list_sys_by_host $HOSTNAME)
		if [[ -z $SYS_NAME ]]; then log ERROR "No SYS_NAME set in function list_sys_by_host"; fi
		pipescript $HOSTNAME $SYS_NAME >> $TMPOUT
	fi
done
#######################################
cat $TMPOUT | sort -n | sed 's/^[0-9]*|/|/g' | sed 's/^|//g'  | grep . > ${TMPOUT}.2 && mv ${TMPOUT}.2 $TMPOUT
ERROR_COUNT=$(cat $TMPOUT | grep ERROR | wc -l | sed 's/ //g')
WARNING_COUNT=$(cat $TMPOUT | grep WARNING | wc -l | sed 's/ //g')
OK_COUNT=$(cat $TMPOUT | grep OK | wc -l | sed 's/ //g')
INFO_COUNT=$(cat $TMPOUT | grep INFO | wc -l | sed 's/ //g')
TOTAL=$(cat $TMPOUT | wc -l  | sed 's/ //g')
#######################################

if [ ! -z "$WEB" ]
then
	cat <<-HTMLCODE
		<!DOCTYPE html
		PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
		<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"> 
		<head> 
			<style type="text/css">
				p {font-family:Arial,sans-serif;}
				caption,th {text-align:center;font-size:18px;font-weight:bold;font-style:italic;}
				td {text-align:center;font-size:14px;}
				.ERROR {background-color:#C4000F;color:#C0C0C0;}
				.WARNING {background-color:#FF6000;color:#000000;}
				.OK {background-color:#008643;color:#C0C0C0;}
				.NOT_VERIFIED {background-color:#C0C0C0;color:#000000;}
				.INFO {background-color:#00999B;color:#C0C0C0;}
			</style>
			<title>ANF Backup check</title> 
			<body> 
			<TABLE align=center BORDER=0 CELLSPACING=2 CELLPADDING=2> 
				<caption>`date`<br>ANF files verification report<br>Command: $0 $@<br> TOTAL=$TOTAL <span class="ERROR"> ERRORS=$ERROR_COUNT </span><span class="WARNING"> WARNING=$WARNING_COUNT </span><span class="OK"> OK=$OK_COUNT </span><span class="INFO"> INFO=$INFO_COUNT </span><span class="NOT_VERIFIED"> NOT_VERIFIED=$NOT_VERIFIED_COUNT </span></caption> 
				<TR class="NOT_VERIFIED"> 
					<TH>SEVERITY</th> 
					<TH>DATE</th> 
					<TH>HOSTS</th> 
					<TH>SID</th> 
					<TH>START</th> 
					<TH>STOP</th> 
					<TH>COMMENT</th> 
				</TR> 
	HTMLCODE
	while read LINE
	do

		SEVERITY=$(echo $LINE | cut -d'|' -f1)
		DATE=$(echo $LINE | cut -d'|' -f2)
		HOSTS=$(echo $LINE | cut -d'|' -f3)
		SYS_NAME=$(echo $LINE | cut -d'|' -f4)
		STARTTIME=$(echo $LINE | cut -d'|' -f5)
		STOPTIME=$(echo $LINE | cut -d'|' -f6)
		COMMENT=$(echo $LINE | cut -d'|' -f7)

		echo "<TR class=\"$SEVERITY\">"
		echo "<TD> $SEVERITY"
		echo "<TD> $DATE"
		echo "<TD> $HOSTS"
		echo "<TD> $SYS_NAME"
		echo "<TD> $STARTTIME"
		echo "<TD> $STOPTIME"
		echo "<TD> $COMMENT"
		echo "</span>"
		echo "</TR>"

	done < $TMPOUT
	echo "</TABLE>"
	echo "</body>"
	echo "</head>"
else
	echo "ANF files verification report"
	echo "TOTAL=$TOTAL ERRORS=$ERROR_COUNT WARNING=$WARNING_COUNT OK=$OK_COUNT INFO=$INFO_COUNT NOT_VERIFIED=$NOT_VERIFIED_COUNT"
	cat $TMPOUT
fi
#######################################
rm $TMPOUT 2>&1 > /dev/null
exit 0
